//
//  LearnSectionViewController.m
//  金融
//
//  Created by Apple on 2018/1/17.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "LearnSectionViewController.h"
#import "LearnSectionCell.h"
#import "JAScrollView.h"
//#import "VideoDetailViewController.h"
#import "HomeWebViewController.h"
//#import "KnowDetailViewController.h"

static NSString * CellID = @"LearnSectionCellID";
@interface LearnSectionViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView    * tableView;
@property (nonatomic,strong)NSMutableArray * dataArray;
@property (nonatomic,strong)NSMutableArray * flagArray;
@property (nonatomic,strong)JAScrollView   * scrollView;
@property (nonatomic,strong)NSMutableArray * imageArray;
@property (nonatomic,strong)NSMutableArray * imageDataArray;
@end

@implementation LearnSectionViewController
- (void)viewDidLoad{
    [super viewDidLoad];
    [self setNavBar];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.barView.mas_bottom);
        make.left.right.mas_equalTo(self.view);
        if (@available(iOS 11.0, *)) {
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        }else{
            make.bottom.mas_equalTo(self.view.mas_bottom);
        }
    }];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableHeaderView = self.scrollView;
    [self networking];
}
- (JAScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[JAScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 164 * SizeWidth)];
    }
    return _scrollView;
}
- (NSMutableArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}
- (NSMutableArray *)imageDataArray
{
    if (!_imageDataArray) {
        _imageDataArray = [NSMutableArray array];
    }
    return _imageDataArray;
}
- (void)setNavBar
{
    [self.barView addSubview:self.titleL];
    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.barView);
        make.width.mas_lessThanOrEqualTo(SCREENWIDTH - 100);
        make.height.mas_greaterThanOrEqualTo(10);
    }];
    self.titleL.text = self.cusTitle;
}
- (void)networking
{
    NSString * url = [NSString stringWithFormat:@"%@%ld",HOST(@"app/stageCourse/list/"),self.type];
    WeakSelf
    [HttpRequest postWithURLString:url parameters:nil showProgressHud:YES success:^(NSDictionary * _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == CODESUCCESS) {
            for (NSDictionary *imgDic in responseObject[@"data"][@"ad"]) {
                [weakSelf.imageArray addObject:imgDic[@"image"][@"path"]];
                [weakSelf.imageDataArray addObject:imgDic];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.scrollView.imagesArray = weakSelf.imageArray;
                [weakSelf.scrollView initView];
                weakSelf.scrollView.block = ^(NSInteger index){
                    [weakSelf pushViewController:index];
                };
            });
            
            [weakSelf.dataArray addObjectsFromArray:responseObject[@"data"][@"content"]];
            for (NSInteger i = 0; i <  weakSelf.dataArray.count; i ++) {
                if (i == 0) {
                    [weakSelf.flagArray addObject:@"1"];
                }else{
                    [weakSelf.flagArray addObject:@"0"];
                }
            }
            if (weakSelf.dataArray.count == 0) {
                weakSelf.tableView.hidden = YES;
                weakSelf.NoDataView.hidden = NO;
            }else{
                weakSelf.tableView.hidden = NO;
                weakSelf.NoDataView.hidden = YES;
            }
            [weakSelf.tableView reloadData];
        }
    } failure:^(NSError * _Nullable error) {
        
    } login:^(BOOL isLogin) {

    }];
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = BGColor;
        [_tableView registerClass:[LearnSectionCell class] forCellReuseIdentifier:CellID];
    }
    return _tableView;
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (NSMutableArray *)flagArray
{
    if (!_flagArray) {
        _flagArray = [NSMutableArray array];
    }
    return _flagArray;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
//设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
//组头高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50.f;
}
//cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.flagArray[indexPath.section] isEqualToString:@"0"])
    {
        return 0;
    }else{
        if ([self.dataArray[indexPath.section][@"sectionList"] isKindOfClass:[NSArray class]]) {
            NSInteger i = [self.dataArray[indexPath.section][@"sectionList"] count];
            if (i % 2 > 0) {
                i = i + 1;
            }
            return 95 * SizeWidth * i / 2 + 15 + 35 * i / 2;
        }else{
            return 0.f;
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if ([self.flagArray[section] isEqualToString:@"0"])
    {
        return 0.f;
    }else{
        if ([self.dataArray count] - 1 == section) {
            return 0.f;
        }
        return 10.f;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 10)];
    view.backgroundColor = BGColor;
    return view;
}
//组头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 50)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel * lineL = [UILabel new];
    [view addSubview:lineL];
    lineL.backgroundColor = LINEColor;
    [lineL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.mas_equalTo(view);
        make.height.mas_offset(0.5);
    }];
    UIImageView * leftV = [UIImageView new];
    [view addSubview:leftV];
    [leftV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.centerY.mas_equalTo(view);
        make.size.mas_offset(CGSizeMake(16, 16));
    }];

    UIImageView * rightV = [UIImageView new];
    [view addSubview:rightV];
    [rightV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-15);
        make.centerY.mas_equalTo(view);
        make.size.mas_offset(CGSizeMake(5, 9));
    }];
    rightV.image = [UIImage imageNamed:@"right_jian"];
    rightV.tintColor = SUBTEXTColor;
    UILabel * moreL = [UILabel new];
    [view addSubview:moreL];
    [moreL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(rightV.mas_left).offset(-10);
        make.centerY.mas_equalTo(view);
        make.width.mas_lessThanOrEqualTo(30);
        make.height.mas_offset(14);
    }];
    moreL.textAlignment = NSTextAlignmentRight;
    moreL.textColor = SUBTEXTColor;
    moreL.font = FONT(14);
    moreL.text = @"更多";
    UIButton * moreBtn = [UIButton new];
    [view addSubview:moreBtn];
    [moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.mas_equalTo(view);
        make.left.mas_equalTo(moreL.mas_left);
    }];
    moreBtn.tag = section;
    [moreBtn addTarget:self action:@selector(clickMoreAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel * titleL = [UILabel new];
    [view addSubview:titleL];
    titleL.font = FONT(17);
    titleL.text = self.dataArray[section][@"courseName"];
    titleL.textColor = TEXTColor;
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(leftV.mas_right).offset(10);
        make.centerY.mas_equalTo(view);
        make.height.mas_offset(20);
        make.right.mas_equalTo(moreBtn.mas_left).offset(-5);
    }];
    
    UIButton * sectionBtn = [UIButton new];
    [view addSubview:sectionBtn];
    [sectionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(leftV.mas_left);
        make.top.bottom.mas_equalTo(view);
        make.right.mas_equalTo(moreBtn.mas_left);
    }];
    sectionBtn.tag = 100 + section;
    [sectionBtn addTarget:self action:@selector(sectionClick:) forControlEvents:UIControlEventTouchUpInside];
    if ([self.flagArray[section] isEqualToString:@"1"]) {
        leftV.image = [UIImage imageNamed:@"Learn_Lower"];
        rightV.hidden = NO;
        moreL.hidden = NO;
        moreBtn.hidden = NO;
    }else{
        leftV.image = [UIImage imageNamed:@"Learn_Right"];
        rightV.hidden = YES;
        moreL.hidden = YES;
        moreBtn.hidden = YES;
    }
    return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WeakSelf
    LearnSectionCell * cell = [[LearnSectionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if ([self.dataArray[indexPath.section][@"sectionList"] isKindOfClass:[NSArray class]]) {
        [cell setDataWithArray:self.dataArray[indexPath.section][@"sectionList"]];
    }
    cell.clickCellImgBlock = ^(NSInteger index) {
        [weakSelf pushVideo:weakSelf.dataArray[indexPath.section][@"sectionList"][index]];
    };
    cell.clipsToBounds = YES;//这句话很重要 不信你就试试
    return cell;
}
- (void)clickMoreAction:(UIButton *)sender
{
//    NSDictionary * dict = self.dataArray[sender.tag];
//    KnowDetailViewController * kv = [[KnowDetailViewController alloc] init];
//    kv.couserId = dict[@"cid"];
//    kv.isCouser = YES;
//    [self.navigationController pushViewController:kv animated:YES];
}
- (void)sectionClick:(UIButton *)sender{
    NSInteger index = sender.tag % 100;
//    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:index];
//    NSArray *indexArray = @[[NSIndexPath indexPathForRow:0 inSection:index]];
    if ([self.flagArray[index] isEqualToString:@"0"]) {
        self.flagArray[index] = @"1";
//        [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];  //使用下面注释的方法就 注释掉这一句
    } else { //收起
        self.flagArray[index] = @"0";
//        [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic]; //使用下面注释的方法就 注释掉这一句
    }
//    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView reloadData];
}
- (void)pushViewController:(NSInteger)index
{
//    NSDictionary * dict = self.imageDataArray[index];
//    if ([dict[@"openMode"] integerValue] == 1) {
//        HomeWebViewController * hc = [[HomeWebViewController alloc] init];
//        hc.cusTitle = dict[@"title"];
//        hc.url = [NSURL URLWithString:dict[@"url"]];
//        hc.imageUrl = dict[@"image"][@"path"];
//        hc.shareUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@?id=%@",OS,@"/wap/app/analysis/info",dict[@"id"]]];
//        [self.navigationController pushViewController:hc animated:YES];
//    }
}
- (void)pushVideo:(NSDictionary *)dict
{
    WeakSelf
    NSString * vid = [NSString stringWithFormat:@"%@",dict[@"videoId"]];
    NSString * sid = [NSString stringWithFormat:@"%@",dict[@"sid"]];
    if (vid.length > 0) {
        [HttpRequest postWithURLString:HOST(@"app/section/play/auth") parameters:@{@"sid":sid,@"videoId":vid,@"vno":VERSION} showProgressHud:YES success:^(NSDictionary * _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == CODESUCCESS) {
//                VideoDetailViewController * vc = [[VideoDetailViewController alloc] init];
//                vc.vid = vid;
//                vc.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@?id=%@&token=%@&pc=1",OS,@"/wap/app/course/info",sid,[HFUser getSaveToken]]];
//                vc.path_auth = responseObject[@"data"][@"playAuth"];
//                [weakSelf presentViewController:vc animated:YES completion:^{
//                    
//                }];
            }
        } failure:^(NSError * _Nullable error) {
            NSLog(@"%@",error);
        } login:^(BOOL isLogin) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf ShowLoginView];
            });
        }];
    }
}
- (void)ShowLoginView
{
    HFLoginView * logView = [HFLoginView shareInit];
    [logView show];
    WeakSelf
    logView.clickPushBlock = ^(NSInteger index) {
        if (index == 0) {
            [weakSelf PushRigest];
        }else{
            [weakSelf PushLogin];
        }
    };
}
- (void)PushRigest
{
    RegisterViewController * rc = [[RegisterViewController alloc] init];
    rc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:rc animated:YES];
}
- (void)PushLogin
{
    LoginViewController * lgvc = [[LoginViewController alloc] init];
    lgvc.myClass = NSStringFromClass([self class]);
    WeakSelf
    lgvc.LoginSuccessBlock = ^{
        [weakSelf networking];
    };
    lgvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:lgvc animated:YES];
}
@end

